package com.maezia.tdr.common;

import com.maezia.tdr.common.enums.StatusCodeEnum;
import com.maezia.tdr.common.exception.TokenExpiredException;
import com.maezia.tdr.common.exception.TooManyException;
import com.maezia.tdr.common.exception.DriveException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("Exception:", e);
        return Result.error(StatusCodeEnum.SYSTEM_ERROR.getCode(), StatusCodeEnum.SYSTEM_ERROR.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result exceptionHandler(HttpRequestMethodNotSupportedException e) {
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(DriveException.class)
    public Result driveExceptionHandler(DriveException e) {
        StatusCodeEnum codeEnum = e.getCodeEnum();
        return Result.error(codeEnum.getCode(), codeEnum.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        String message = result.getFieldError().getDefaultMessage();
        return Result.error(message);
    }

    @ExceptionHandler(TooManyException.class)
    public Result tooManyExceptionHandler(TooManyException e) {
        return Result.error(StatusCodeEnum.TOO_MANY_REQUEST.getCode(), StatusCodeEnum.TOO_MANY_REQUEST.getMessage());
    }

    @ExceptionHandler(TokenExpiredException.class)
    public Result tokenExpiredExceptionHandler(TokenExpiredException e) {
        return Result.error(StatusCodeEnum.TOKEN_EXPIRED.getCode(), StatusCodeEnum.TOKEN_EXPIRED.getMessage());
    }
}
